package com.hucsmn.stumansys.servlet.student;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.hucsmn.stumansys.entity.Admin;
import com.hucsmn.stumansys.entity.Student;
import com.hucsmn.stumansys.service.StudentService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * 学生信息删除 API。
 *
 * 接收 HTTP 参数
 *      id      学生信息 ID。逗号分隔的列表，也可以提供多个参数。
 *
 * 响应 JSON 数据
 *      code    状态码。0 表示成功，1 表示失败，2 表示权限错误。
 *      msg     操作出错原因。
 *
 * 备注
 *      要求 session.login 必须是 Admin 且非空。
 *
 * @author hucsmn
 */
@WebServlet("/api/student/remove")
public class StudentRemoveServlet extends HttpServlet {
    private final StudentService studentService = StudentService.getInstance();
    private final Gson gson = new GsonBuilder().create();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        int[] ids = ConvertUtils.parseIdLists(request.getParameterValues("id"));

        JsonObject result = new JsonObject();
        HttpSession session = request.getSession();
        if (!(session.getAttribute("login") instanceof Admin)) {
            result.addProperty("code", 2);
            result.addProperty("msg", "没有权限");
        } else if (!studentService.remove(ids)) {
            result.addProperty("code", 1);
            if (ids.length > 1) {
                result.addProperty("msg", "未成功删除所有指定学生信息");
            } else {
                result.addProperty("msg", "未成功删除学生信息");
            }
        } else {
            result.addProperty("code", 0);
            result.addProperty("msg", "");
        }

        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
}
